package cn.gy.securityservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity//Spring项目总需要添加此注解，SpringBoot项目中不需要
//@EnableMethodSecurity
public class WebSecurityConfig {

//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser( //此行设置断点可以查看创建的user对象
//                User
//                        .withDefaultPasswordEncoder()
//                        .username("huan") //自定义用户名
//                        .password("password") //自定义密码
//                        .roles("USER") //自定义角色
//                        .build()
//        );
//        return manager;
//    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //authorizeRequests()：开启授权保护
        //anyRequest()：对所有请求开启授权保护
        //authenticated()：已认证请求会自动被授权
        http
                .authorizeRequests(
                        authorize -> authorize
                                //具有USER_LIST权限的用户可以访问/user/list
                                .requestMatchers("/user/list").hasAuthority("USER_LIST")
                                //具有USER_ADD权限的用户可以访问/user/add
                                .requestMatchers("/user/add").hasAuthority("USER_ADD")
                                //对所有请求开启授权保护
                                .anyRequest()
                                //已认证的请求会被自动授权
                                .authenticated()
                )

                .httpBasic(withDefaults())//;//基本授权方式

                .formLogin(form -> {
                    form
                            .loginPage("/login").permitAll() //登录页面无需授权即可访问
                            .usernameParameter("username") //自定义表单用户名参数，默认是username
                            .passwordParameter("password") //自定义表单密码参数，默认是password
                            .successHandler(new ProductAuthenticationSuccessHandler()) //认证成功时的处理
                            .failureHandler(new ProductAuthenticationFailureHandler())
                    //.failureUrl("/login?error") //登录失败的返回地址
                    ;
                }); //使用表单授权方式
        //.formLogin(withDefaults())//表单授权方式
        http.logout(logout -> {
            logout.logoutSuccessHandler(new ProductLogoutSuccessHandler()); //注销成功时的处理
        });
        http.exceptionHandling(exception -> {
            exception.authenticationEntryPoint(new ProductAuthenticationEntryPoint());//请求未认证的接口
            exception.accessDeniedHandler(new ProductAccessDeniedHandler());
        });
        http.cors(withDefaults());
        //关闭csrf攻击防御
        http.csrf((csrf) -> {
            csrf.disable();
        });
        //会话管理
        http.sessionManagement(session -> {
            session
                    .maximumSessions(1)
                    .expiredSessionStrategy(new ProductSessionInformationExpiredStrategy());
        });
        return http.build();
    }

//    @Bean
//    public UserDetailsService userDetailsService2() {
//        DBUserDetailsManager manager = new DBUserDetailsManager();
//        return manager;
//    }
}